package com.qimei.onerice.servlet;
import com.qimei.onerice.entity.Customer;
import com.qimei.onerice.service.CustomerService;
import com.qimei.onerice.service.impl.CustomerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updatePassword")
public class UpdatePasswordServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String customerId = request.getParameter("customerId");
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");


		CustomerService customerService = new CustomerServiceImpl();
		Customer customer = customerService.getCustomerById(Integer.parseInt(customerId));
		String truePassword = customer.getCustomerPassword();

		if (oldPassword != null && newPassword != null && confirmPassword != null) {
			if (!newPassword.equals(confirmPassword)) {
				// 新密码与确认密码不匹配，返回修改失败
				request.setAttribute("error", "新密码与旧密码不匹配");
				request.getRequestDispatcher("/view/updatePassword.jsp").forward(request, response);
			} else {
				if (oldPassword.equals(truePassword)) {
					// 返回修改成功
					customer.setCustomerPassword(newPassword);
					customerService.updateCustomer(customer);
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("密码修改成功");
				} else {
					// 旧密码不匹配，返回修改失败
					response.setCharacterEncoding("UTF-8");
					response.getWriter().write("旧密码不正确");
				}
			}
		} else {
			// 参数不完整，返回修改失败
			response.getWriter().write("请填完表单");
		}

	}
}
